/**
 * 拖拽
 * @param {Object} obj 参数对象
 */


let cursorDrag  = (obj) => {
    new CursorDrag(obj);
}

class CursorDrag {
    constructor(obj) {
        this.obj = obj;

        this.el = obj.el ? document.querySelector(obj.el) : '';
        this.type = obj.type || 'random'; // top-bottom left-right random

        this.startX;  // 按住
        this.startY;
        this.moveX;   // 移动
        this.moveY;
        this.endX;    // 抬起
        this.endY;

        this.init();
    }

}

Object.assign(CursorDrag.prototype, {
    init() {
        let el = this.el;
        el.addEventListener('mousedown', this.dowm.bind(this));
    },
    dowm(e) {
        e = e || window.event;
        this.startX = e.clientX;
        this.startY = e.clientY;

        this.preserveMove = this.move.bind(this);
        this.preserveEnd = this.end.bind(this);
        document.addEventListener('mousemove', this.preserveMove);
        document.addEventListener('mouseup', this.preserveEnd);

        this.obj.dowm(this.startX, this.startY);
    },
    move(e) {
        this.moveX = e.clientX;
        this.moveY = e.clientY;

        this.obj.moveFn(this.moveX, this.moveY);
    },
    end(e) {
        e = e || window.event;
        this.endX = e.clientX;
        this.endY = e.clientY;

        document.removeEventListener('mousemove', this.preserveMove);
        document.removeEventListener('mouseup', this.preserveEnd);
        this.preserveMove = null;
        this.preserveEnd = null;

        this.obj.endFn(this.endX, this.endY);
    },
});


export {cursorDrag}
